package lingou.homework.postbar.controller.tool;

import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import lingou.homework.postbar.domain.Identity;
import lingou.homework.postbar.domain.User;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class JsonHelper {

    public static class Entry{
        String key;
        Object value;
        protected Entry(String key, Object value) {
            this.key = key;
            this.value = value;
        }
    }

//    public static class MapEntry{
//        String key;
//        Function<Object, Object> value;
//        protected MapEntry(String key, Function<Object, Object> value) {
//            this.key = key;
//            this.value = value;
//        }
//    }

    public static Entry of(String key, Object value){
        return new Entry(key, value);
    }
//    public static MapEntry ofMap(String key, Function<Object, Object> value){
//        return new MapEntry(key, value);
//    }
    public static JsonNode attach(Object obj1, Entry...entries){
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode1 = objectMapper.valueToTree(obj1);
        if(jsonNode1 instanceof ObjectNode objectNode){
            for (Entry entry : entries) {
                objectNode.set(entry.key, objectMapper.valueToTree(entry.value));
            }
            return jsonNode1;
        }
        return null;
    }

    public static ObjectNode fill(Object obj, Map.Entry<String, Function<JsonNode, Entry>>...idMaps) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Function<JsonNode, Entry>> idMap = Map.ofEntries(idMaps);
        JsonNode jsonNode = objectMapper.valueToTree(obj);
        if (jsonNode instanceof ObjectNode objectNode) {
            idMap.forEach((k, f) -> {
                JsonNode child = objectNode.get(k);
                if(child != null){
                    Entry ne = f.apply(child);
                    objectNode.remove(k);
                    objectNode.set(ne.key, objectMapper.valueToTree(ne.value));
                }
            });
            return objectNode;
        }
        return null;
    }
//
//    public static JsonNode unionObject(Object obj1, Object obj2, String name1, String name2){
//
//    }

}
